//
//  ViewController.m
//  UI03_CustomView
//
//  Created by Scott on 16/5/5.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "ViewController.h"
#import "LTView.h"

@interface ViewController () <UITextFieldDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createCustomView];

}

#pragma mark - 知识点1: 自定义View
- (void)createCustomView {

    // 详见 LTView (包含label和textField控件).
    LTView *viewOfUser = [LTView ltViewWithFrame:CGRectMake(30, 60, self.view.frame.size.width - 60, 40) title:@"用户名:" placeHolder:@"请输入用户名"];
    
    [self.view addSubview:viewOfUser];
    viewOfUser.textField.delegate = self;
    
    
    // 密码
    LTView *viewOfPasswd = [LTView ltViewWithFrame:CGRectMake(30, 120, self.view.frame.size.width - 60, 40) title:@"密码:" placeHolder:@"请输入密码"];
    [self.view addSubview:viewOfPasswd];
    viewOfPasswd.textField.delegate = self;
    

}

#pragma mark - TextField Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    // 限制文本长度.
//    return [self limitTextLengthV1:textField range:range string:string];
    
//    return [self limitTextLengthV2:textField range:range string:string];
    
    // 限制文本内容
    return [self limitTextContentV1:textField range:range string:string];
    
    
}

- (BOOL)limitTextContentV1:(UITextField *)textField range:(NSRange)range string:(NSString *)string {
    
    NSArray *arr = @[@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"0"];
    
    for (int i = 0; i < 10; i++) {
        if ([string isEqualToString:arr[i]]) {
            return NO;
        }
    }
    
    return YES;
}

- (BOOL)limitTextLengthV2:(UITextField *)textField range:(NSRange)range string:(NSString *)string {
    
    if (range.location > 10) {
        return NO;
    } else {
        return YES;
    }
}

- (BOOL)limitTextLengthV1:(UITextField *)textField range:(NSRange)range string:(NSString *)string {
    
    if (textField.text.length > 10) {
        textField.text = [textField.text substringToIndex:10];
        
    }
    return YES;
    
}


@end
